<template>
	<view>
		<view class="list">
			<checkbox-group @change="CheckboxChange">
				<scroll-view :scroll-y="isScroll" :style="{ height: windowHeight + 'px' }">
					<block :key="index" v-for="(item, index) in dataList">
						<view :data-index="index" class="order-item" @touchstart="drawStart" @touchmove="drawMove"
							@touchend="drawEnd" :style="{ right: item.right + 'rpx' }">
							<view class="content flex align-center justify-between">
								<checkbox :checked="item.checked" class='round' :value="index"></checkbox>
								<image :src="item.img_url"></image>
								<view class="content-right flex flex-direction">
									<text>{{item.title}}</text>
									<view class="flex align-center justify-between">
										<text class="text-price">{{item.price}}</text>
										<view class="num align-center flex">
											<view @click="reduce(index)">-</view>
											<view>{{item.num}}</view>
											<view @click="add(index)">+</view>
										</view>
									</view>
								</view>
							</view>
							<view class="remove" @click="delItem(index)">删除</view>
						</view>
					</block>

					<!-- #ifdef MP-ALIPAY -->
					<view class="empty"><u-empty mode="car" v-if="dataList.length==0"></u-empty></view>
					<!-- #endif -->
					<!-- #ifdef MP-WEIXIN -->
					<view class="empty">暂无商品，快去选购吧</view>
					<!-- #endif -->
				</scroll-view>
			</checkbox-group>
			<view class="flex solid-bottom padding justify-center">
				<text class="loadMore">{{loadStr}}</text>
			</view>
		</view>
		<view class="bottom flex align-center justify-between">
			<view class="bottom-left flex align-center">
				<checkbox :checked="isSelectAll" @change="all" class='round' :value="inde"></checkbox>
				<text>全选</text>
				<view v-if="haveSelect" class="bottom-left-text">
					<view class="flex align-end">
						<text>合计</text>
						<text class="text-price">{{totalPrice}}</text>
					</view>
					<text>共{{total}}件</text>
				</view>
			</view>
			<view class="bottom-btn" @tap='toPay'>去结算</view>
		</view>
	</view>
</template>

<script>
	var api = require('@/components/api.js');
	export default {
		data() {
			return {
				refreshing: false,
				loadStr: '加载中...',
				fetchPageNum: 1,
				delBtnWidth: 160,
				dataList: [
					// { checked:false, right: 0 ,num:0 ,price:600}
				],
				shoppingCartCount: '',
				shoppingCartList: [],
				isScroll: true,
				windowHeight: 0,
				isSelectAll: false,
				haveSelect: false,
				total: 0,
				totalPrice: 0,
				user_id: '',
				inde: ''
			};
		},
		onShow() {

			this.loadUser()
			var that = this;
			wx.getSystemInfo({
				success: function(res) {
					that.windowHeight = res.windowHeight;
				}
			});
			this.user_id = uni.getStorageSync('user').user_id
			this.loadShoppingCartList()
			this.loadShopCartCount()
		},
		onLoad: function(options) {
			/* uni.showToast({
				title:'onload'
			}) */
			this.loadUser()
			var that = this;
			wx.getSystemInfo({
				success: function(res) {
					that.windowHeight = res.windowHeight;
				}
			});
			this.user_id = uni.getStorageSync('user').user_id
			this.loadShoppingCartList()
			this.loadShopCartCount()
		},
		onReachBottom() {
			console.log('滑动到页面底部')
			this.loadShoppingCartList();
		},
		onPullDownRefresh() {
			console.log('下拉刷新');
			this.refreshing = true;
			this.loadShoppingCartList();
		},
		onShow() {
			console.log('shopCart onShow');
			this.loadShoppingCartList();
			this.loadShopCartCount();
		},
		methods: {
			loadShopCartCount: function() {
				console.info('loadShopCartCount user_id:' + this.user_id)
				api.get({
					url: 'Goods/GetShoppingCartCount',
					data: {
						user_id: this.user_id
					},
					success: data => {
						console.info('loadShopCartCount' + JSON.stringify(data))
						if (data.ErrCode == 0) {
							this.shoppingCartCount = data.Response
						}
					}
				});
			},
			/**
			 * 加载购物车列表
			 * **/
			loadShoppingCartList: function() {
				console.info('loadShoppingCartList user_id:' + this.user_id)
				api.get({
					url: 'Goods/GetShoppingCartList',
					data: {
						user_id: this.user_id
					},
					success: data => {
						console.info('loadShoppingCartList' + JSON.stringify(data))
						if (data.ErrCode == 0) {
							this.shoppingCartList = data.Response
							var select_list = uni.getStorageSync('car_select');
							console.log(select_list);
							var change_num = 0;
							this.total = 0
							this.totalPrice = 0
							for (var i = 0; i < this.shoppingCartList.length; i++) {
								var a = select_list.indexOf(i)
								if (a > -1) {
									this.shoppingCartList[i].checked = true
									this.totalPrice += this.$public.priceFormat(this.shoppingCartList[i]
										.sell_price, 2) * parseInt(this.shoppingCartList[i].quantity)
									this.total += parseInt(this.shoppingCartList[i].quantity)
									change_num++
								} else {
									this.shoppingCartList[i].checked = false
								}

								this.shoppingCartList[i].right = 0
								this.shoppingCartList[i].num = parseInt(this.shoppingCartList[i].quantity)
								this.shoppingCartList[i].price = this.$public.priceFormat(this
									.shoppingCartList[i].sell_price, 2)
							}
							if (change_num == this.shoppingCartList.length) {
								this.isSelectAll = true
							} else {
								this.isSelectAll = false
							}

							if (change_num > 0) {
								// console.log('all dataList2 '+JSON.stringify(this.dataList))
								this.totalPrice = parseFloat(this.totalPrice).toFixed(2)
								this.haveSelect = true
							}



							this.dataList = this.shoppingCartList

							console.log('this.dataList', this.dataList)
							this.refreshing = false;
							uni.stopPullDownRefresh();
							this.loadStr = '已经到底了'
						} else {
							this.dataList = []
							this.isSelectAll = false
							this.haveSelect = false
						}
					}
				});
			},
			/**
			 * 删除购物车商品
			 * **/
			deleteShoppingCart: function(cart_id) {
				api.post({
					url: 'Goods/PostShoppingCartDelete?user_id=' + this.user.user_id,
					data: {
						idlist: [{
							id: cart_id
						}],

					},
					success: data => {
						console.log(JSON.stringify(data));
						if (data.ErrCode == 0) {
							uni.showToast({
								title: '删除成功'
							})
						}
					}
				});
			},
			/**
			 * 修改购物车商品数量
			 * **/
			changeShopCartCount: function(item) {
				api.get({
					url: 'Goods/GetShoppingCartNumEdit',
					data: {
						cart_id: item.cart_id,
						quantity: item.quantity
					},
					success: data => {
						console.info('changeShopCartCount' + JSON.stringify(data))
						if (data.ErrCode == 0) {
							uni.showToast({
								title: '修改成功'
							})
						}
					}
				});
			},
			loadUser: function() {
				try {
					this.user = uni.getStorageSync('user');
					if (this.user == '') {
						// uni.showModal({
						// 	title: '提示',
						// 	content: '请登陆',
						// 	success: (res) => {
						// 		if (res.confirm) {
						// 			uni.navigateTo({
						// 				url: '/pages/login/login'
						// 			});
						// 		}
						// 	}
						// });
					}
					console.log(this.user);
				} catch (e) {
					// uni.showModal({
					// 	title: '提示',
					// 	content: '账号超时，请重新登陆',
					// 	success: (res) => {
					// 		if (res.confirm) {
					// 			uni.navigateTo({
					// 				url: '/pages/login/login'
					// 			});
					// 		}
					// 	}
					// });
				}
			},
			toPay: function() {
				var dataTemp = [{}]
				var j = 0
				var isChecked = false
				console.log('toPay:' + JSON.stringify(this.dataList))
				console.log(this.dataList);
				for (var i = 0; i < this.dataList.length; i++) {
					var select_list = uni.getStorageSync('car_select');
					console.log(select_list);
					var a = select_list.indexOf(i)
					if (a > -1 || this.isSelectAll) {
						var temp = {
							cart_id: 0,
							goods_id: '',
							quantity: 0,
							goods_type: 1,
							sku_id: ''
						}
						if (this.dataList[i].cart_id) {
							temp.cart_id = this.dataList[i].cart_id
						} else {
							temp.cart_id = 0
						}
						temp.goods_id = this.dataList[i].goods_id
						temp.goods_type = 1
						temp.quantity = this.dataList[i].quantity
						temp.sku_id = this.dataList[i].sku_id
						dataTemp[j] = temp
						j++
						isChecked = true
					}
				}
				if (!isChecked) {
					uni.showToast({
						title: '请选择商品'
					})
					return;
				}
				uni.showLoading({
					title: '下单...'
				});
				api.post({
					url: 'Order/PostOrderShow?user_id=' + this.user.user_id,
					data: {
						data: dataTemp,

					},
					success: data => {
						uni.hideLoading();
						console.log(JSON.stringify(data));
						if (data.ErrCode == 0) {
							uni.removeStorageSync('car_select');
							uni.navigateTo({
								url: '/pages/confirmOrder/confirmOrder?key=' + JSON.stringify(data
									.Response)
							})
						}
					}
				});
			},
			reduce: function(ind) {
				if (this.dataList[ind].num > 0) {
					this.dataList[ind].num = --this.dataList[ind].num
				}
				this.dataList = [].concat(this.dataList)
				var item = {
					cart_id: 0,
					quantity: 0
				}
				item.cart_id = this.dataList[ind].cart_id
				item.quantity = this.dataList[ind].num
				this.totalPrice -= this.dataList[ind].price
				this.totalPrice = parseFloat(this.totalPrice).toFixed(2)
				this.changeShopCartCount(item)
			},
			add: function(ind) {
				this.dataList[ind].num = ++this.dataList[ind].num
				this.dataList = [].concat(this.dataList)
				var item = {
					cart_id: 0,
					quantity: 0
				}
				item.cart_id = this.dataList[ind].cart_id
				item.quantity = this.dataList[ind].num
				console.log('price', this.dataList[ind].price)
				this.totalPrice = Number(this.totalPrice) + Number(this.dataList[ind].price)
				this.totalPrice = parseFloat(this.totalPrice).toFixed(2)
				this.changeShopCartCount(item)
			},
			all: function() {
				console.log('all:' + this.isSelectAll)
				if (this.isSelectAll) { //不勾选
					this.dataList.forEach(item => {
						item.checked = false
					})
					console.log('all dataList0 ', this.dataList)
					// console.log('all dataList0 '+JSON.stringify(this.dataList))
					this.haveSelect = false
					this.isSelectAll = false
					this.total = 0
					this.totalPrice = 0
				} else {
					this.total = 0
					this.totalPrice = 0
					// console.log('all dataList1 '+JSON.stringify(this.dataList))
					this.dataList.forEach(item => {
						item.checked = true
						this.totalPrice += item.price * item.num
						this.total += item.num
					})
					// console.log('all dataList2 '+JSON.stringify(this.dataList))
					this.totalPrice = parseFloat(this.totalPrice).toFixed(2)
					this.isSelectAll = true
					this.haveSelect = true
					console.log('shopCart all:' + this.totalPrice)
					console.log('this.dataList', this.dataList)
				}
				this.dataList = [].concat(this.dataList)
			},
			CheckboxChange: function(e) {
				console.log(e);
				var selectList = e.detail.value;
				var s = []
				var totalPrice = 0;
				var total = 0;
				console.log('CheckboxChange:' + JSON.stringify(selectList))
				uni.setStorageSync('car_select', JSON.stringify(selectList));
				selectList.forEach((item) => {
					this.dataList[item].checked = true
					if (this.dataList[item].checked) {
						s.push(this.dataList[item].checked)
						totalPrice += this.dataList[item].price * this.dataList[item].num
						total += this.dataList[item].num
					}
				})

				if (s.length > 0) {
					this.haveSelect = true
				} else {
					this.haveSelect = false
				}
				if (s.length == this.dataList.length) {
					this.isSelectAll = true
				} else {
					for (var i = 0; i < this.dataList.length; i++) {
						for (var j = 0; j < selectList.length; j++) {
							if (i == selectList[j]) {
								break;
							} else {
								//this.dataList[i].checked = false
							}
						}
					}
					this.isSelectAll = false
				}
				// console.log('CheckboxChange list:'+JSON.stringify(this.dataList) )
				this.totalPrice = parseFloat(totalPrice).toFixed(2)
				this.total = total
				this.dataList = [].concat(this.dataList)
			},
			drawStart: function(e) {
				// console.log("drawStart");
				var touch = e.touches[0];
				for (var index in this.dataList) {
					this.dataList[index].right = 0;
				}
				this.startX = touch.clientX;
			},
			drawMove: function(e) {
				var touch = e.touches[0];
				var item = this.dataList[e.currentTarget.dataset.index];
				var disX = this.startX - touch.clientX;

				if (disX >= 20) {
					if (disX > this.delBtnWidth) {
						disX = this.delBtnWidth;
					}
					this.isScroll = false;
					this.dataList[e.currentTarget.dataset.index].right = disX;
				} else {
					this.isScroll = true;
					this.dataList[e.currentTarget.dataset.index].right = 0;
				}
			},
			drawEnd: function(e) {
				var item = this.dataList[e.currentTarget.dataset.index];
				if (item.right >= this.delBtnWidth / 2) {
					this.isScroll = true;
					this.dataList[e.currentTarget.dataset.index].right = this.delBtnWidth;
				} else {
					this.isScroll = true;
					this.dataList[e.currentTarget.dataset.index].right = 0;
				}
			},
			delItem: function(ind) {
				console.log('delItem:' + ind)
				console.log('delItem:' + JSON.stringify(this.dataList[ind]))
				this.deleteShoppingCart(this.dataList[ind].cart_id)
				this.dataList.splice(ind, 1)
				this.dataList.forEach(item => {
					item.checked = false
				})
				this.isSelectAll = false
				this.haveSelect = false
				this.total = 0
				this.totalPrice = 0
				console.log('delItem:' + JSON.stringify(this.dataList))

			}
		}
	};
</script>

<style lang="scss" scoped>
	.empty {
		height: 600rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.bottom-left-text {
		margin-left: 42upx;
	}

	.bottom-left-text>view>text:nth-child(2) {
		font-size: 32upx;
		color: #ee0000;
		margin-left: 4upx;
	}

	.bottom-left-text>view>text:nth-child(1),
	.bottom-left-text>text {
		font-size: 24upx;
		color: #999999;
	}

	.bottom-left>text {
		font-size: 28upx;
		color: #000000;
	}

	.bottom-left checkbox {
		margin-left: 10upx;
		margin-right: 10upx;
	}

	.bottom-btn {
		width: 200upx;
		height: 66upx;
		background-color: $btn-bground;
		border-radius: 33upx;
		text-align: center;
		line-height: 66upx;
		color: #fff;
		font-size: 30upx;
	}

	.num {
		width: 200upx;
		height: 50upx;
		border-radius: 10upx;
		border: solid 1upx #cccccc;
	}

	.num>view:nth-child(1),
	.num>view:nth-child(3) {
		width: 50upx;
		height: 50upx;
		text-align: center;
		line-height: 50upx;
		font-size: 28upx;
		color: #333333;
	}

	.num>view:nth-child(2) {
		width: 100upx;
		text-align: center;
		line-height: 50upx;
		border-left: solid 1upx #cccccc;
		border-right: solid 1upx #cccccc;
		font-size: 28upx;
		color: #333333;
	}

	.content-right>view {
		margin-top: 20upx;
	}

	.content-right {
		width: 416upx;
		margin-left: 20upx;
	}

	.content-right>text {
		font-size: 28upx;
		color: #000000;
	}

	.content>image {
		width: 213upx;
		height: 160upx
	}

	.content checkbox {
		margin-left: 10upx;
		margin-right: 10upx;
	}

	.bottom {
		height: 100upx;
		width: 100%;
		background-color: #ffffff;
		position: fixed;
		bottom: 0;
		border: 1px solid #ddd;
	}

	.order-item {
		height: 205upx;
		width: 100%;
		display: flex;
		position: relative;
		background-color: #fff;
		border-bottom: 1upx solid #ddd;
	}

	.remove {
		width: 160upx;
		height: 100%;
		background-color: #009829;
		color: white;
		position: absolute;
		top: 0;
		right: -160upx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>